package jwlee.testmail;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {
	private String sender = "nothisaddress@sw.com";// 发件人地址
	private String smtpHost = "172.16.7.253";// 邮件发送服务器（smtp）
	private String user = null; // 登录用户名
	private String password = null;// 登录密码
	private String subject = "Test Javamail!";// mail主题

	public MailSender() {
		this.setPropertiesAttri("MailSender.properties");
	}

	private void setPropertiesAttri(String resourceName) {
		InputStream is = getClass().getResourceAsStream(resourceName);
		Properties prop = new Properties();
		try {
			prop.load(is);

			this.setSmtpHost((String) prop.get("SmtpHost"));
			this.setUser((String) prop.get("User"));
			this.setPassword((String) prop.get("Password"));
			this.setSender((String) prop.get("Sender"));
			this.setSubject((String) prop.get("Subject"));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void setSender(String sender) {
		this.sender = sender;
	}

	public String getSender() {
		return sender;
	}

	public void setSmtpHost(String smtpHost) {
		this.smtpHost = smtpHost;
	}

	public String getSmtpHost() {
		return smtpHost;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getUser() {
		return user;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getSubject() {
		return subject;
	}

	/**
	 * 使用smtp发送邮件 主程序
	 * 
	 * @throws MessagingException
	 *             mail发送失败
	 */
	public void smtp(String receiver, String content) throws MessagingException {
		if (smtpHost == null)
			throw new MessagingException("smtpHost not found");

		Properties props = new Properties();
		props.put("mail.smtp.host", smtpHost);// 设置smtp主机

		Authenticator auth = null;
		if (user != null && password != null) {
			props.put("mail.smtp.auth", "true");// 使用smtp身份验证
			auth = new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(user, password);
				}
			};
		}
		// 获得邮件会话对象
		Session session = Session.getDefaultInstance(props, auth);

		// 创建MIME邮件对象
		MimeMessage mimeMsg = new MimeMessage(session);
		if (sender != null) {
			mimeMsg.setFrom(new InternetAddress(sender));
		}
		if (receiver != null) {
			mimeMsg.setRecipients(Message.RecipientType.TO, this
					.parse(receiver));
		}
		if (subject != null) {
			mimeMsg.setSubject(subject);
		}

		Multipart multipart = new MimeMultipart();
		// 正文
		MimeBodyPart contentpart = new MimeBodyPart();
		contentpart.setText(content == null ? "" : content, "GBK");
		contentpart.setContent((String) content, "text/html;charset=GBK");// 设置邮件格式为html
		multipart.addBodyPart(contentpart);// 在 Multipart 中增加mail内容
		// 附件
		BodyPart affixpart = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(
				"src/jwlee/testmail/MailSender.properties");
		affixpart.setDataHandler(new DataHandler(fileds));
		affixpart.setFileName(fileds.getName());
		multipart.addBodyPart(affixpart);// 在 Multipart 中增加mail附件
		// 增加 Multipart 到信息体
		mimeMsg.setContent(multipart);

		mimeMsg.setSentDate(new Date());// 设置发送日期

		Transport.send(mimeMsg);// 发送邮件
		System.out.println("邮件发送成功!");
	}

	InternetAddress[] parseAddress(String addressStr) {
		try {
			return InternetAddress.parse(addressStr, true);
		} catch (AddressException e) {
			System.err.println("Could not parse address [" + addressStr + "]. "
					+ e.getMessage());
		}
		return null;
	}

	/** 解析地址集合字符串 */
	private InternetAddress[] parse(String addressSet) throws AddressException {
		List<InternetAddress> list = new ArrayList<InternetAddress>();
		StringTokenizer tokens = new StringTokenizer(addressSet, ";");
		while (tokens.hasMoreTokens()) {
			list.add(new InternetAddress(tokens.nextToken().trim()));
		}
		InternetAddress[] addressArray = new InternetAddress[list.size()];
		list.toArray(addressArray);

		return addressArray;
	}

	// 供外部调用的接口
	public boolean sendMails(String to, String content) {
		if (to == null || content == null) {
			return false;
		}

		try {
			this.smtp(to, content);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return true;
	}

	// for test
	public static void main(String[] args) {
		MailSender mail = new MailSender();
		String to = "lijianwei@sw.com";
		String content = "ok";
		mail.sendMails(to, content);
	}

}